/*
 * Copyright (C) 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tools.idea.layoutinspector.runningdevices.ui.rendering

import java.awt.Component
import java.awt.event.MouseEvent
import java.awt.event.MouseListener
import java.awt.event.MouseMotionListener
import java.awt.event.MouseWheelEvent
import java.awt.event.MouseWheelListener

/**
 * A mouse listener that forwards its events to the component provided by [componentProvider] if
 * [shouldForward] returns true.
 */
internal class ForwardingMouseListener(
  private val componentProvider: () -> Component,
  private val shouldForward: () -> Boolean,
) : MouseListener, MouseWheelListener, MouseMotionListener {
  override fun mouseClicked(e: MouseEvent) = forwardEvent(e)

  override fun mousePressed(e: MouseEvent) = forwardEvent(e)

  override fun mouseReleased(e: MouseEvent) = forwardEvent(e)

  override fun mouseEntered(e: MouseEvent) = forwardEvent(e)

  override fun mouseExited(e: MouseEvent) = forwardEvent(e)

  override fun mouseWheelMoved(e: MouseWheelEvent) = forwardEvent(e)

  override fun mouseDragged(e: MouseEvent) = forwardEvent(e)

  override fun mouseMoved(e: MouseEvent) = forwardEvent(e)

  private fun forwardEvent(e: MouseEvent) {
    if (shouldForward()) {
      componentProvider().dispatchEvent(e)
    }
  }
}
